package com.ymt.bpm.service.platform.fauth.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ymt.bpm.dao.MDao;
import com.ymt.bpm.dao.Mapper;
import com.ymt.bpm.model.Const.Oplog;
import com.ymt.bpm.model.PPos;
import com.ymt.bpm.service.platform.fauth.FaPosService;
import com.ymt.bpm.service.platform.log.OpLogService;
import com.ymt.bpm.util.Const;
import com.ymt.bpm.util.DateUtil;
import com.ymt.bpm.util.DhxUtil;
import com.ymt.bpm.util.EncodeUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Johnny on 2017/2/20.
 */
@Service
public class FaPosServiceImpl implements FaPosService {


    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MDao mDao;

    @Autowired
    private OpLogService oplog;

    @Override
    public JSONObject allByTenant(String tenantId, String queryParams, int timezoneOffset) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        if (queryParams!=null && queryParams.length()>0) {
            paramMap.putAll(JSONObject.parseObject(queryParams));
        }
        paramMap.put(Const.TENANT_ID, tenantId);
        if (paramMap.containsKey("search") && paramMap.get("search")!=null) {
            paramMap.put("search", EncodeUtil.decode((String)paramMap.get("search")));
        }
        int offset = (int)paramMap.get("offset");
        List<PPos> list = mDao.selectList("PPosMapper", "selectAllByTenant", paramMap);
        int total = mDao.selectOne("PPosMapper", "selectAllByTenantCount", paramMap);
        JSONObject rtn = new JSONObject();
        JSONArray rows = new JSONArray();
        if (list!=null && list.size()>0) {
            for (PPos pos : list) {
                JSONObject node = DhxUtil.toJsonWithDateAli(pos, Const.LANG_ZH, timezoneOffset);
                node.put("_ITEM_NO", ++offset);
                rows.add(node);
            }
        }
        rtn.put("rows", rows);
        rtn.put("total", total);
        return rtn;
    }

    @Override
    public JSONObject get(String tenantId, String posId, String lang, int timezoneOffset) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put(Const.TENANT_ID, tenantId);
        paramMap.put("posId", posId);
        PPos pos = mDao.selectOne("PPosMapper", "selectByPrimaryKey", paramMap);
        JSONObject rtn = DhxUtil.toFastJsonWithDate(pos, lang, timezoneOffset);
        return rtn;
    }

    @Override
    public String checkAttr(String tenantId, String attrName, String value, String posId) {
        if (log.isDebugEnabled()) {
            log.debug("checkAttr tenantId="+tenantId);
            log.debug("checkAttr attrName="+attrName);
            log.debug("checkAttr value="+value);
            log.debug("checkAttr posId="+posId);
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("tenantId", tenantId);
        paramMap.put("value", value);
        paramMap.put("posId", posId);
        int rs = mDao.selectOne("PPosMapper", "checkAttr"+ StringUtils.capitalize(attrName), paramMap);
        if (log.isDebugEnabled()) {
            log.debug("checkAttr rs="+rs);
        }
        return rs>0 ? "false" : "true";
    }

    @Override
    public JSONObject save(String tenantId, String loginName, String displayName, PPos pos) {
        if (tenantId!=null) {
            pos.setTenantId(Integer.parseInt(tenantId));
        }
        int rs = 0;
        if (pos.getPosId()==null || pos.getPosId().length()==0) {
            pos.setPosId("POS-"+ UUID.randomUUID().toString());
            pos.setCreator(loginName);
            pos.setCreatorName(displayName);
            pos.setCreateTime(DateUtil.getGMTDate());
            rs += mDao.insert("PPosMapper", "insertSelective", pos);

            //记录日志
            oplog.bizlog(tenantId, loginName, displayName, null, Oplog.OP.CREATE, Oplog.CODE.POS, pos.getPosName());
        } else {
            pos.setUpdator(loginName);
            pos.setUpdatorName(displayName);
            pos.setUpdateTime(DateUtil.getGMTDate());
            rs += mDao.update("PPosMapper", "updateByPrimaryKeySelective", pos);

            //记录日志
            oplog.bizlog(tenantId, loginName, displayName, null, Oplog.OP.UPDATE, Oplog.CODE.POS, pos.getPosName());
        }
        JSONObject rtn = new JSONObject();
        rtn.put("result", rs);
        return rtn;
    }

    @Override
    public JSONObject delete(String tenantId, String loginName, String displayName, String posId) {
        JSONObject rtn = new JSONObject();
        int rs = 0;
        //TODO check reference in process

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put(Const.TENANT_ID, tenantId);
        paramMap.put("posId", posId);
        
        PPos pos = mDao.selectOne(Mapper.PPosMapper, "selectByPrimaryKey", paramMap);

        //check reference in org-pos
        List<Map<String, Object>> refList = mDao.selectList(Mapper.POrgPosMapper, "selectPosReferedByOrg", paramMap);
        if (refList!=null && refList.size()>0) {
            StringBuilder names = new StringBuilder();
            for (Map<String, Object> map : refList) {
                if (names.length()>0) {
                    names.append(",");
                }
                names.append(map.get("ORG_NAME"));
            }
            rtn.put("referedOrgs", names);
            return rtn;
        }

        rs = mDao.delete("PPosMapper", "deleteByPrimaryKey", paramMap);
        rtn.put("result", rs);

        //记录日志
        oplog.bizlog(tenantId, loginName, displayName, null, Oplog.OP.DELETE, Oplog.CODE.POS, pos.getPosName());
        
        return rtn;
    }

    @Override
    public String queryDhx(String tenantId, String queryParams,
                           int fInd, int lInd,
                           int timezoneOffset, String lang, String ordercolumns) {
        log.debug("queryDhx queryParams="+queryParams);
        Map<String, Object> params = new HashMap<String,Object>();
        Map<String, Object> bo = new HashMap<String,Object>();
        if (queryParams!=null) {
            bo.putAll(JSONObject.parseObject(queryParams));
        }
        if (tenantId!=null) {
            bo.put(Const.TENANT_ID, tenantId);
        }
        params.put("bo", bo);
        params.put("fromRow", fInd-1);
        params.put("toRow", lInd);
        params.put("rows", lInd - fInd + 1);
        params.put("timezoneOffset", timezoneOffset);
        params.put("orderby", DhxUtil.parseGridOrderBy(ordercolumns));
        log.debug("queryDhx params="+params);
        List<Map<String,?>> list = mDao.selectList("PPosMapper", "pagingSelect", params);
        int total = mDao.selectOne("PPosMapper", "pagingSelectCount", params);
        String[] cols = new String[]{"POS_ID", "POS_NAME", "POS_DESC", "CREATOR", "CREATE_TIME", "UPDATOR", "UPDATE_TIME"};
        String rtn= DhxUtil.toGridJsonStr(list,
                cols, fInd, total, timezoneOffset, lang);
        log.debug("queryDhx returns:\n"+rtn);
        return rtn;
    }
}
